// pages/orderlist/orderlist.js
var common = require("../../public");
var url = common.url;
var APP_ID = common.APP_ID;
var md5 = common.md5Start;
Page({

    /**
     * 页面的初始数据
     */
    data: {
        navindex: 1, //导航 1：全部  2：拍卖中  3：已拍中  4：待发货  5：待收货  6：已完成 7：已取消
        orderlist: [],
        temp_id: '', //临时订单id（删除订单用）
        delmask: false, //是否显示 删除订单弹框  true：显示    false：不显示
        listData: [], //倒计时测试用===========================
    },
	//立即付款按钮
	order_payorder:function(e){
		var id = e.currentTarget.dataset.id;//订单id
		wx.navigateTo({
			url: '../order_confirm/order_confirm?orderid='+id,
		})
	},

    /**
     * 倒计时
     */
    setCountDown: function() {
        let time = 1000;
        let {
            listData
        } = this.data;
        let list = listData.map((v, i) => {
            if (v.remainTime) {
                if (v.remainTime <= 0) {
                    v.remainTime = 0;
                    return;
                }
                let formatTime = this.getFormat(v.remainTime);
                v.remainTime -= time;
                v.countDown = `${formatTime.hh}:${formatTime.mm}:${formatTime.ss}`;

            } else {
                v.countDown = '00:00:00'; //============做判断   如果没有倒计时的话
            }
            return v;

        })
        this.setData({
            listData: list
        });
        setTimeout(this.setCountDown, time);
    },

    /**
     * 格式化时间
     */
    getFormat: function(msec) {
        let ss = parseInt(msec / 1000);
        let ms = parseInt(msec % 1000);
        let mm = 0;
        let hh = 0;
        if (ss > 60) {
            mm = parseInt(ss / 60);
            ss = parseInt(ss % 60);
            if (mm > 60) {
                hh = parseInt(mm / 60);
                mm = parseInt(mm % 60);
            }
        }
        ss = ss > 9 ? ss : `0${ss}`;
        mm = mm > 9 ? mm : `0${mm}`;
        hh = hh > 9 ? hh : `0${hh}`;
        return {
            ms,
            ss,
            mm,
            hh
        };
    }, //计时器结束
    base64_encode: function(str) { // 编码，配合encodeURIComponent使用
        var c1, c2, c3;
        var base64EncodeChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
        var i = 0,
            len = str.length,
            strin = '';
        while (i < len) {
            c1 = str.charCodeAt(i++) & 0xff;
            if (i == len) {
                strin += base64EncodeChars.charAt(c1 >> 2);
                strin += base64EncodeChars.charAt((c1 & 0x3) << 4);
                strin += "==";
                break;
            }
            c2 = str.charCodeAt(i++);
            if (i == len) {
                strin += base64EncodeChars.charAt(c1 >> 2);
                strin += base64EncodeChars.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));
                strin += base64EncodeChars.charAt((c2 & 0xF) << 2);
                strin += "=";
                break;
            }
            c3 = str.charCodeAt(i++);
            strin += base64EncodeChars.charAt(c1 >> 2);
            strin += base64EncodeChars.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));
            strin += base64EncodeChars.charAt(((c2 & 0xF) << 2) | ((c3 & 0xC0) >> 6));
            strin += base64EncodeChars.charAt(c3 & 0x3F)
        }
        console.log(strin)
        return strin
    },

    base64_decode: function(input) { // 解码，配合decodeURIComponent使用
        var that = this;
        var base64EncodeChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
        var output = "";
        var chr1, chr2, chr3;
        var enc1, enc2, enc3, enc4;
        var i = 0;
        input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
        while (i < input.length) {
            enc1 = base64EncodeChars.indexOf(input.charAt(i++));
            enc2 = base64EncodeChars.indexOf(input.charAt(i++));
            enc3 = base64EncodeChars.indexOf(input.charAt(i++));
            enc4 = base64EncodeChars.indexOf(input.charAt(i++));
            chr1 = (enc1 << 2) | (enc2 >> 4);
            chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
            chr3 = ((enc3 & 3) << 6) | enc4;
            output = output + String.fromCharCode(chr1);
            if (enc3 != 64) {
                output = output + String.fromCharCode(chr2);
            }
            if (enc4 != 64) {
                output = output + String.fromCharCode(chr3);
            }
        }
        return that.utf8_decode(output);
    },
    utf8_decode: function(utftext) { // utf-8解码
        var string = '';
        let i = 0;
        let c = 0;
        let c1 = 0;
        let c2 = 0;
        while (i < utftext.length) {
            c = utftext.charCodeAt(i);
            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            } else if ((c > 191) && (c < 224)) {
                c1 = utftext.charCodeAt(i + 1);
                string += String.fromCharCode(((c & 31) << 6) | (c1 & 63));
                i += 2;
            } else {
                c1 = utftext.charCodeAt(i + 1);
                c2 = utftext.charCodeAt(i + 2);
                string += String.fromCharCode(((c & 15) << 12) | ((c1 & 63) << 6) | (c2 & 63));
                i += 3;
            }
        }
        return string;
    },
    //跳转订单详情
    go_order_detail: function(e) {
        var id = e.currentTarget.dataset.id; //获取订单id
        wx.navigateTo({
            url: '../orderdetail/orderdetail?id=' + id
        })
    },
    //关闭 删除订单弹框
    closeDelAlert: function(e) {
        this.setData({
            delmask: false,
            temp_id: '', //将临时订单id换成需要删除的实际id
            del_index: '', //要删除的订单下标
        })
    },
    //点击删除订单按钮
    delorder: function(e) {
        this.setData({
            delmask: true
        })
    },
    changeNav: function(e) {
        var that = this;
        var navindex = e.currentTarget.dataset.nav;
		var activeNav = e.currentTarget.dataset.id;//当前选择的nav的id
        that.setData({
            navindex: navindex,
            page: 1,
            showNoneData: false, //隐藏无订单数据提示
			activeNav: activeNav
        })
        that.navFunc(navindex)
    },
    //切换导航 公共函数
    navFunc: function(navindex) {
        var that = this;
        wx.showLoading({
            title: '加载中',
            mask: true,
        })
        var sonUrl = ''; //接口名称
        if (navindex == 1) {
            //全部订单
			sonUrl = 'Order/allOrder'
        }
        
        if (navindex == 3) {
            //已拍中订单
			sonUrl = 'Order/aucedList'
        }
        if (navindex == 4) {
            //4：待发货订单
            sonUrl = 'Order/waitShipList'
        }
        if (navindex == 5) {
            //待收货订单
            sonUrl = 'Order/waitReceiptList'
        }
        if (navindex == 6) {
            //已完成订单
            sonUrl = 'Order/completeList'
        }
        if (navindex == 7) {
            //已取消订单
            sonUrl = 'Order/cancelList'
        }
        var session_str = wx.getStorageSync('session_str'); //获取密钥
        wx.request({
            url: url + sonUrl,
            data: {
                session_str: session_str,
                page: 1,
                APP_ID: APP_ID,
                sign: md5([
                    "session_str" + session_str,
                    "page1",
                    "APP_ID" + APP_ID,
                ])
            },
            header: {},
            method: 'post',
            dataType: 'json',
            responseType: 'text',
            success: function(res) {
                wx.hideLoading();
                if (res.data.code == 200) {
                    that.setData({
                        orderlist: res.data.data, //订单数据
                    })
                    if (res.data.data.length == 0) {
                        that.setData({
                            showNoneData: true
                        })
                    }
                } else {
                    wx.showToast({
                        title: res.data.msg,
                        icon: 'none',
                        mask: true,
                    })
                }
            },
            fail: function(res) {
                wx.hideLoading();
                wx.showToast({
                    title: '网络错误',
                    icon: 'none',
                    mask: true,
                })
            }
        });
    },
    //删除订单（显示是否删除提示）
    order_handleorder: function(e) {
        var id = e.currentTarget.dataset.id; //订单id
        var index = e.currentTarget.dataset.index; //订单index
        this.setData({
            delmask: true,
            temp_id: id, //将临时订单id换成需要删除的实际id
            del_index: index, //要删除的订单下标
        })
    },
    //去评价
    handle_appraise: function(e) {
        var id = e.currentTarget.dataset.id; //订单id
        wx.navigateTo({
            url: '../pingjia_order/pingjia_order?id=' + id,
        })
    },
    //确认收货
    confirm_reveive: function(e) {
        var that = this;
        var index = e.currentTarget.dataset.index; //数据下标
        var id = e.currentTarget.dataset.id; //订单id
        var orderlist = this.data.orderlist; //订单数据列表
        var session_str = wx.getStorageSync('session_str'); //获取密钥
        wx.showModal({
            content: '确认收货？',
            showCancel: true,
            cancelText: '取消',
            confirmText: '确定',
            success: function(res) {
                if (res.confirm) {
                    wx.request({
                        url: url + 'Order/receipt',
                        data: {
                            session_str: session_str,
                            order_id: id,
                            APP_ID: APP_ID,
                            sign: md5([
                                "session_str" + session_str,
                                "order_id" + id,
                                "APP_ID" + APP_ID,
                            ])
                        },
                        header: {},
                        method: 'post',
                        dataType: 'json',
                        responseType: 'text',
                        success: function(res) {
                            wx.hideLoading();
                            if (res.data.code == 200) {
                                orderlist.splice(index, 1);
                                that.setData({
                                    orderlist: orderlist,
                                    delmask: false,
                                })
                                wx.showToast({
                                    title: '操作成功',
                                    icon: 'success',
                                    mask: true,
                                })
                                if (orderlist.length == 0) {
                                    that.setData({
                                        showNoneData: true,
                                    })
                                }

                            } else {
                                wx.showToast({
                                    title: res.data.msg,
                                    icon: 'none',
                                    mask: true,
                                })
                            }
                        },
                        fail: function(res) {
                            wx.hideLoading();
                            wx.showToast({
                                title: '网络错误',
                                icon: 'none',
                                mask: true,
                            })
                        }
                    });
                }
            },
        })

    },
    //确定删除订单
    handle_del_order: function(e) {
        var that = this;
        var id = this.data.temp_id; //临时订单id
        var del_index = this.data.del_index; //临时订单下标
        var session_str = wx.getStorageSync('session_str'); //获取密钥
        var orderlist = this.data.orderlist; //订单数据列表
        wx.request({
            url: url + 'Order/deleteOrder',
            data: {
                session_str: session_str,
                order_id: id,
                APP_ID: APP_ID,
                sign: md5([
                    "session_str" + session_str,
                    "order_id" + id,
                    "APP_ID" + APP_ID,
                ])
            },
            header: {},
            method: 'post',
            dataType: 'json',
            responseType: 'text',
            success: function(res) {
                wx.hideLoading();
                if (res.data.code == 200) {
                    orderlist.splice(del_index, 1);
                    that.setData({
                        orderlist: orderlist,
                        delmask: false,
                    })
                    wx.showToast({
                        title: '操作成功',
                        icon: 'success',
                        mask: true,
                    })
                    if (orderlist.length == 0) {
                        that.setData({
                            showNoneData: true,
                        })
                    }

                } else {
                    wx.showToast({
                        title: res.data.msg,
                        icon: 'none',
                        mask: true,
                    })
                }
            },
            fail: function(res) {
                wx.hideLoading();
                wx.showToast({
                    title: '网络错误',
                    icon: 'none',
                    mask: true,
                })
            }
        });
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {
		var navindex = options.num ? options.num:1;
		this.setData({
			navindex: navindex
		})
        
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function() {
        var that = this;
        var navindex = this.data.navindex; //nav 
        that.setData({
            page: 1
        })
        var session_str = wx.getStorageSync('session_str'); //获取密钥
        var sonUrl = ''; //接口名称
        if (navindex == 1) {
            //全部订单
			sonUrl = 'Order/allOrder'
        }
        if (navindex == 3) {
            //已拍中订单
			sonUrl = 'Order/aucedList'
        }
        if (navindex == 4) {
            //4：待发货订单
            sonUrl = 'Order/waitShipList'
        }
        if (navindex == 5) {
            //待收货订单
            sonUrl = 'Order/waitReceiptList'
        }
        if (navindex == 6) {
            //已完成订单
            sonUrl = 'Order/completeList'
        }
        if (navindex == 7) {
            //已取消订单
            sonUrl = 'Order/cancelList'
        }
        var session_str = wx.getStorageSync('session_str'); //获取密钥
        wx.request({
            url: url + sonUrl,
            data: {
                session_str: session_str,
                page: 1,
                APP_ID: APP_ID,
                sign: md5([
                    "session_str" + session_str,
                    "page1",
                    "APP_ID" + APP_ID,
                ])
            },
            header: {},
            method: 'post',
            dataType: 'json',
            responseType: 'text',
            success: function(res) {
                wx.hideLoading();
                if (res.data.code == 200) {
                    that.setData({
                        orderlist: res.data.data, //订单数据
                    })
                    if (res.data.data.length == 0) {
                        that.setData({
                            showNoneData: true
                        })
                    }
                } else {
                    wx.showToast({
                        title: res.data.msg,
                        icon: 'none',
                        mask: true,
                    })
                }
            },
            fail: function(res) {
                wx.hideLoading();
                wx.showToast({
                    title: '网络错误',
                    icon: 'none',
                    mask: true,
                })
            }
        });
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function() {
		var that = this;
		var navindex = this.data.navindex; //nav 
		var page = this.data.page;//页码
		page++;
		var session_str = wx.getStorageSync('session_str'); //获取密钥
		var sonUrl = ''; //接口名称
		if (navindex == 1) {
			//全部订单
			sonUrl = 'Order/allOrder'
		}
		// if (navindex == 2) {
		// 	//拍卖中
		// 	sonUrl = 'Order/cancelList'
		// }
		if (navindex == 3) {
			//已拍中订单
			sonUrl = 'Order/cancelList'
		}
		if (navindex == 4) {
			//4：待发货订单
			sonUrl = 'Order/waitShipList'
		}
		if (navindex == 5) {
			//待收货订单
			sonUrl = 'Order/waitReceiptList'
		}
		if (navindex == 6) {
			//已完成订单
			sonUrl = 'Order/completeList'
		}
		if (navindex == 7) {
			//已取消订单
			sonUrl = 'Order/cancelList'
		}
		var session_str = wx.getStorageSync('session_str'); //获取密钥
		var orderlist = this.data.orderlist;//订单数据列表
		wx.request({
			url: url + sonUrl,
			data: {
				session_str: session_str,
				page: page,
				APP_ID: APP_ID,
				sign: md5([
					"session_str" + session_str,
					"page"+page,
					"APP_ID" + APP_ID,
				])
			},
			header: {},
			method: 'post',
			dataType: 'json',
			responseType: 'text',
			success: function (res) {
				wx.hideLoading();
				if (res.data.code == 200) {
					var result = res.data.data;
					orderlist = orderlist.concat(result)
					that.setData({
						orderlist: orderlist, //订单数据
						page:page
					})
					if (res.data.data.length == 0) {
						wx.showToast({
							title: '没有更多数据',
							icon: 'none',
							mask: true,
						})
					}
				} else {
					wx.showToast({
						title: res.data.msg,
						icon: 'none',
						mask: true,
					})
				}
			},
			fail: function (res) {
				wx.hideLoading();
				wx.showToast({
					title: '网络错误',
					icon: 'none',
					mask: true,
				})
			}
		});
    },

})